package com.data.boot.config;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.watch.SimpleWatcher;
import cn.hutool.core.io.watch.WatchMonitor;
import cn.hutool.core.io.watch.watchers.DelayWatcher;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.data.boot.service.ScriptService;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.io.File;
import java.nio.file.Path;
import java.nio.file.WatchEvent;


/**
 * Created by dwk on 2019/5/31.
 * 实时监控并加载groovy脚本
 */
@Component
public class GroovyScriptMonitor implements ApplicationRunner {
    private static final Log log = LogFactory.get();


    @Value(value = "${root.path}")
    public String rootPath;
    @Autowired
    private ScriptService scriptService;


    @Override
    public void run(ApplicationArguments args) {
        File file = new File(rootPath);
        //延迟处理监听事件,合并多次修改事件
        WatchMonitor watchMonitor = WatchMonitor.create(file, WatchMonitor.ENTRY_DELETE, WatchMonitor.ENTRY_MODIFY);
        watchMonitor.setWatcher(new DelayWatcher(new SimpleWatcher() {
            @Override
            public void onModify(WatchEvent<?> event, Path currentPath) {
                Object obj = event.context();
                log.info("修改：{}-> {}", currentPath, obj);
                String name = String.valueOf(obj);
                if (FileUtil.extName(name).equals("groovy")) {//过滤非groovy脚本
                    scriptService.loadScript(currentPath + File.separator + name);
                }
            }

            @Override
            public void onDelete(WatchEvent<?> event, Path currentPath) {
                Object obj = event.context();
                String name = String.valueOf(obj);
                log.info("删除：{}-> {}", currentPath, obj);
                if (FileUtil.extName(name).equals("groovy")) {
                    scriptService.unloadScript(currentPath + File.separator + name);
                }
            }
        }, 3000));
        //启动监听
        log.info("启动Groovy脚本监听:" + rootPath + "....");
        watchMonitor.setMaxDepth(2).start();//目录深度为2
    }
}